package com.yyl.fmall.user.interceptor;

import com.yyl.fmall.user.exception.IllegalCharacterException;
import com.yyl.fmall.utils.CommonConstants;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @BelongsProject: fmall
 * @BelongsPackage: com.yyl.fmall.user.interceptor
 * @Author: YuanSir
 * @CreateTime: 2022-11-04  14:04
 * @Description:
 * @Version: 1.0
 */

/**
 * 检查请求中的token是否合法
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
        //放行浏览器的跨域预检请求
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        
        String token = request.getHeader("token");
    
        try {
            Jwts.parser().setSigningKey(CommonConstants.JWT_SECRET_KEY).parse(token);
        } catch (ExpiredJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) {
            throw new IllegalCharacterException("Token有问题，请重新登录！");
        }
        
        //把请求放行
        return true;
    }
}
